import 'dart:io';
import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import 'package:flutter/foundation.dart';

class ATTService {
  static const String _attStatusKey = 'att_status_checked';
  static const int _maxRetryAttempts = 5;
  static const Duration _retryDelay = Duration(seconds: 2);

  /// 检查并请求App Tracking Transparency权限
  /// 使用循环重试机制确保弹窗能够正常显示
  /// 利用Flutter单线程机制，必须等待用户响应才能继续
  static Future<TrackingStatus> requestTrackingPermission() async {
    // 只在iOS平台执行
    if (!Platform.isIOS) {
      if (kDebugMode) {
        print('ATT: Not iOS platform, skipping ATT request');
      }
      return TrackingStatus.notSupported;
    }

    try {
      // 检查当前追踪状态
      TrackingStatus currentStatus = await AppTrackingTransparency.trackingAuthorizationStatus;
      
      if (kDebugMode) {
        print('ATT: Current tracking status: $currentStatus');
      }

      // 如果已经有明确的状态（允许或拒绝），直接返回
      if (currentStatus == TrackingStatus.authorized || 
          currentStatus == TrackingStatus.denied ||
          currentStatus == TrackingStatus.restricted) {
        if (kDebugMode) {
          print('ATT: Already have definitive status: $currentStatus');
        }
        return currentStatus;
      }

      // 如果状态是notDetermined，需要请求权限
      if (currentStatus == TrackingStatus.notDetermined) {
        if (kDebugMode) {
          print('ATT: Status is notDetermined, requesting permission with retry mechanism');
        }
        
        return await _requestWithRetry();
      }

      return currentStatus;
    } catch (e) {
      if (kDebugMode) {
        print('ATT: Error during permission request: $e');
      }
      return TrackingStatus.notSupported;
    }
  }

  /// 带重试机制的权限请求
  /// 确保弹窗能够正常显示，避免无调起的情况
  static Future<TrackingStatus> _requestWithRetry() async {
    for (int attempt = 1; attempt <= _maxRetryAttempts; attempt++) {
      try {
        if (kDebugMode) {
          print('ATT: Attempt $attempt of $_maxRetryAttempts to request tracking permission');
        }

        // 再次检查状态，确保仍然需要请求
        TrackingStatus preRequestStatus = await AppTrackingTransparency.trackingAuthorizationStatus;
        
        if (preRequestStatus != TrackingStatus.notDetermined) {
          if (kDebugMode) {
            print('ATT: Status changed to $preRequestStatus before request, returning');
          }
          return preRequestStatus;
        }

        // 请求权限 - 这里会阻塞等待用户响应
        if (kDebugMode) {
          print('ATT: Calling requestTrackingAuthorization()...');
        }
        
        TrackingStatus requestedStatus = await AppTrackingTransparency.requestTrackingAuthorization();
        
        if (kDebugMode) {
          print('ATT: Received response: $requestedStatus');
        }

        // 验证返回的状态是否有效
        if (requestedStatus != TrackingStatus.notDetermined) {
          if (kDebugMode) {
            print('ATT: Successfully got definitive status: $requestedStatus');
          }
          return requestedStatus;
        }

        // 如果仍然是notDetermined，可能是弹窗没有正常显示
        if (kDebugMode) {
          print('ATT: Still notDetermined after request, attempt $attempt failed');
        }

        // 如果不是最后一次尝试，等待后重试
        if (attempt < _maxRetryAttempts) {
          if (kDebugMode) {
            print('ATT: Waiting ${_retryDelay.inSeconds} seconds before retry...');
          }
          await Future.delayed(_retryDelay);
        }

      } catch (e) {
        if (kDebugMode) {
          print('ATT: Error in attempt $attempt: $e');
        }
        
        // 如果不是最后一次尝试，等待后重试
        if (attempt < _maxRetryAttempts) {
          await Future.delayed(_retryDelay);
        }
      }
    }

    // 所有重试都失败了，返回当前状态
    if (kDebugMode) {
      print('ATT: All retry attempts failed, checking final status');
    }
    
    try {
      TrackingStatus finalStatus = await AppTrackingTransparency.trackingAuthorizationStatus;
      if (kDebugMode) {
        print('ATT: Final status after all retries: $finalStatus');
      }
      return finalStatus;
    } catch (e) {
      if (kDebugMode) {
        print('ATT: Error getting final status: $e');
      }
      return TrackingStatus.notSupported;
    }
  }

  /// 获取当前追踪状态
  static Future<TrackingStatus> getCurrentStatus() async {
    if (!Platform.isIOS) {
      return TrackingStatus.notSupported;
    }

    try {
      return await AppTrackingTransparency.trackingAuthorizationStatus;
    } catch (e) {
      if (kDebugMode) {
        print('ATT: Error getting current status: $e');
      }
      return TrackingStatus.notSupported;
    }
  }

  /// 检查是否需要显示ATT弹窗
  static Future<bool> shouldRequestPermission() async {
    if (!Platform.isIOS) {
      return false;
    }

    try {
      TrackingStatus status = await AppTrackingTransparency.trackingAuthorizationStatus;
      return status == TrackingStatus.notDetermined;
    } catch (e) {
      if (kDebugMode) {
        print('ATT: Error checking if should request permission: $e');
      }
      return false;
    }
  }

  /// 获取追踪状态的用户友好描述
  static String getStatusDescription(TrackingStatus status) {
    switch (status) {
      case TrackingStatus.authorized:
        return 'Tracking authorized';
      case TrackingStatus.denied:
        return 'Tracking denied';
      case TrackingStatus.notDetermined:
        return 'Tracking permission not determined';
      case TrackingStatus.restricted:
        return 'Tracking restricted';
      case TrackingStatus.notSupported:
        return 'Tracking not supported';
    }
  }
} 